package com.notary.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.notary.config.TencentProperties;
import com.notary.entity.*;
import com.notary.entity.vo.JsonResult;
import com.notary.service.*;
import com.notary.util.HttpUtil;
import com.notary.util.JuHeUtil;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 腾讯云 rtc 服务
 *
 * @author Administrator
 */
@Controller
@Slf4j
@Api(tags = "腾讯云RTC服务接口")
public class TencentRtcController {

    @Autowired
    TLSSigAPIv2 tlsSigAPIv2;

    @Autowired
    TencentProperties tencentProperties;

    @Autowired
    private JuHeUtil juHeUtil;

    @Autowired
    private PersonService personService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private NotaryService notaryService;

    @Autowired
    private ContractCurrentStatusService contractCurrentStatusService;

    private static final String PERSON_VIDEO_TEMPLATE_NO = "232435";

    private static final String NOTARY_VIDEO_TEMPLATE_NO = "234733";

    @Value("${baidu.dwz.dwzUrl}")
    private String dwzUrl;

    @Value("${baidu.dwz.dwzToken}")
    private String dwzToken;

    @Value("${baidu.dwz.dwzValidDate}")
    private String dwzValidDate;

    @Value("${office.name}")
    private String gzName;


    @ApiOperation(value = "腾讯云RTC密钥", notes = "腾讯云RTC密钥")
    @GetMapping("/getUserSig")
    @ResponseBody
    public JsonResult getUserSig(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        Map<String, Object> map = new HashMap<>();
        map.put("userSig", tlsSigAPIv2.genUserSig(userId, 604800));
        map.put("sdkAppId", tencentProperties.getSdkAppId());
        return JsonResult.success(map);
    }


    @GetMapping("/index.html")
    @ApiOperation(value = "跳转腾讯云视频页面", notes = "跳转腾讯云视频页面")
    public String index(HttpServletRequest request) {
        String array = request.getParameter("roomId");
        if (StringUtils.isNotEmpty(array)) {
            String[] a = array.split("_");
            request.setAttribute("userId", a[0]);
            request.setAttribute("roomId", a[1]);
        }
        return "index";
    }

    @PostMapping("/sendMsgToUser")
    @ApiOperation(value = "发送短信通知当事人或者公证员视频连线", notes = "发送短信通知当事人或者公证员视频连线")
    @ResponseBody
    public JsonResult sendMsgToUser(@RequestBody JSONObject jsonObject) {
        String videoUrl = jsonObject.getString("videoUrl");
        String contractId = jsonObject.getString("contractId");
        //flag:0表示当事人 1：表示公证员
        Integer flag = jsonObject.getInteger("flag");
        if (StringUtils.isBlank(contractId) || StringUtils.isBlank(videoUrl) || Objects.isNull(flag)) {
            return JsonResult.fail("视频连线错误！");
        }
        //获取百度短网址
        JsonResult result0 = null;
        JsonResult result1 = null;
        if (Objects.equals(0,flag)) {
            result0 = HttpUtil.getShortUrl(dwzUrl, videoUrl, dwzToken,dwzValidDate);
        }else if (Objects.equals(1,flag)) {
            result1 = HttpUtil.getShortUrl(dwzUrl, videoUrl, dwzToken,dwzValidDate);
        }
        //发送消息给当事人
        if (!Objects.isNull(result0) && Objects.equals("200",result0.getCode())) {
            String newDwzUrl = result0.getData().toString();
            //根据卷宗id获取卷宗
            QueryWrapper<ContractCurrentStatus> currentStatusQueryWrapper = new QueryWrapper<>();
            currentStatusQueryWrapper.eq("contract_id", contractId);
            currentStatusQueryWrapper.orderByDesc("create_time");
            ContractCurrentStatus contractCurrentStatus = contractCurrentStatusService.list(currentStatusQueryWrapper).get(0);
            Notary notary = notaryService.getById(contractCurrentStatus.getOwner());
            //根据卷宗id查询当事人信息
            QueryWrapper<Person> queryWrapper = new QueryWrapper();
            queryWrapper.eq("contract_id",contractId);
            Person person = personService.getOne(queryWrapper);
            Map<String,String> param = new HashMap<>(4);
            param.put("name",person.getName());
            param.put("gzName",gzName);
            param.put("notaryName",notary.getName());
            param.put("roomUrl",newDwzUrl);
            if (StringUtils.isNotBlank(person.getPhone())) {
//                juHeUtil.sendSms("13822163063",PERSON_VIDEO_TEMPLATE_NO,param);
                juHeUtil.sendSms(person.getPhone(),PERSON_VIDEO_TEMPLATE_NO,param);
            }
            return JsonResult.success();
        }
        //发送消息给公证员
        if (!Objects.isNull(result1) && Objects.equals("200",result1.getCode())) {
            String newDwzUrl = result1.getData().toString();
            //根据卷宗id获取卷宗
            QueryWrapper<ContractCurrentStatus> currentStatusQueryWrapper = new QueryWrapper<>();
            currentStatusQueryWrapper.eq("contract_id", contractId);
            currentStatusQueryWrapper.orderByDesc("create_time");
            ContractCurrentStatus contractCurrentStatus = contractCurrentStatusService.list(currentStatusQueryWrapper).get(0);
            Notary notary = notaryService.getById(contractCurrentStatus.getOwner());
            //根据卷宗id查询当事人信息
            QueryWrapper<Person> queryWrapper = new QueryWrapper();
            queryWrapper.eq("contract_id",contractId);
            Person person = personService.getOne(queryWrapper);
            Map<String,String> param = new HashMap<>(4);
            param.put("name",person.getName());
            param.put("gzName",gzName);
            param.put("notaryName",notary.getName());
            param.put("roomUrl",newDwzUrl);
            if (StringUtils.isNotBlank(notary.getPhone())) {
//                juHeUtil.sendSms("13822163063",NOTARY_VIDEO_TEMPLATE_NO,param);
                juHeUtil.sendSms(notary.getPhone(),NOTARY_VIDEO_TEMPLATE_NO,param);
            }
            return JsonResult.success();
        }
        return JsonResult.fail("获取百度短网址失败！");
    }
}
